﻿using System;
using System.IO;
using System.Xml;
using Presentation;

namespace Infrastructure
{
    public class HtmlLogger : ILogger
    {
        public string Name { get; private set; }
        public bool CanWriteTimeMarks { get; private set; }

        private XmlDocument xmlLog;

        public HtmlLogger(bool canWriteTimeMarks = true)
        {
            CanWriteTimeMarks = canWriteTimeMarks;
            var creationTime = DateTime.Now.ToString("yyyy-MMM-dd_HH-mm-ss");
            Name = creationTime + "_" + "log.html";
            CreateXmlDocument();
        }

        private void CreateXmlDocument()
        {
            xmlLog = new XmlDocument();

            var html = CreateChildElement("html", xmlLog);
            var head = CreateChildElement("head", html);

            var title = CreateChildElement("title", head);
            title.InnerText = Name;

            var style = CreateChildElement("style", head); 
            style.SetAttribute("type", "text/css");
            style.InnerText = "pre {line-height: 0.1em; }";

            CreateChildElement("body", html); 
            
            xmlLog.Save(Name);
        }

        private XmlElement CreateChildElement(string tag, XmlNode parent)
        {
            return parent.AppendChild(xmlLog.CreateElement(tag)) as XmlElement;
        }

        public void Write(string text, bool writeTimeMark = true)
        {
            var body = xmlLog.GetElementsByTagName("body")[0];
            var pre = CreateChildElement("pre", body);
            var time = DateTime.Now.ToString("HH:mm:ss");

            if (CanWriteTimeMarks)
            {
                if (writeTimeMark)
                {
                    pre.InnerText += "[" + time + "] ";
                }
                else
                {
                    pre.InnerText += "           ";
                }
            }
            pre.InnerText += text;

            xmlLog.Save(Name);
        }

        public string Read()
        {
            var text = "";
            using (var reader = new StreamReader(Name))
            {
                while (!reader.EndOfStream)
                {
                    text += reader.ReadLine();
                }
                reader.Close();
            }
            return text;
        }
    }
}
